<template>
  <div class="login-container">
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    >
      <template #right>
        <van-button type="primary" size="small" round @click="goToRegister">去注册</van-button>
      </template>
    </van-nav-bar>

    <van-form @submit="handleSubmit" class="login-form">
      <van-cell-group>
        <van-cell title="登录方式" is-link @click="toggleLoginMode">
          <template #title>
            登录方式
          </template>
          <template #label>
            当前登录方式：{{ loginMode === 'password' ? '密码登录' : '验证码登录' }}
          </template>
        </van-cell>

        <van-field
          v-if="loginMode === 'password'"
          v-model="username"
          label="用户名"
          placeholder="请输入用户名"
          required
        />

        <van-field
          v-if="loginMode === 'password'"
          v-model="password"
          type="password"
          label="密码"
          placeholder="请输入密码"
          required
        />

        <van-field
          v-if="loginMode === 'code'"
          v-model="phone"
          label="手机号"
          placeholder="请输入手机号"
          required
        />

        <van-field
          v-if="loginMode === 'code'"
          v-model="code"
          label="验证码"
          placeholder="请输入验证码"
          required
          @click-right-icon="sendVerificationCode"
        >
          <template #button>
            <span v-if="!countdown" class="send-code-button" @click="sendVerificationCode">发送验证码</span>
            <span v-else class="send-code-button">{{ countdown }}秒后重新发送</span>
          </template>
        </van-field>

        <van-checkbox v-model="agreeTerms" required>同意《用户协议》</van-checkbox>
      </van-cell-group>

      <van-button type="primary" block @click="handleSubmit" class="login-button">登录</van-button>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { NavBar as VanNavBar, RadioGroup as VanRadioGroup, Radio as VanRadio, Cell as VanCell, Field as VanField, Checkbox as VanCheckbox, CellGroup as VanCellGroup, Form as VanForm, Button as VanButton } from 'vant';
import  request  from '@/utils/request'; // 引入 request 方法

const router = useRouter();

const loginMode = ref('password');
const username = ref('dark');
const password = ref('123456');
const phone = ref('15244667237');
const code = ref('');
const agreeTerms = ref(false);
const countdown = ref<number | null>(null);

function setLoginMode(mode: string) {
  loginMode.value = mode;
}

function toggleLoginMode() {
  loginMode.value = loginMode.value === 'password' ? 'code' : 'password';
}

function goToRegister() {
  router.push('/register');
}

function validatePhoneNumber(phoneNumber: string): boolean {
  const regex = /^1[3-9]\d{9}$/;
  return regex.test(phoneNumber);
}

function sendVerificationCode() {
  if (!validatePhoneNumber(phone.value)) {
    showToast('请输入有效的11位手机号码');
    return;
  }

  // 使用 request 方法发起请求
  const config = {
    url: '/code',
    method: 'GET',
    params: { phone: phone.value }
  };

  request(config)
    .then((data) => {
      console.log(data);
      // 将data中的data下的code的值 回显到 验证码输入框
      code.value = data.data.code;
      showToast('验证码已发送');
      startCountdown();
    })
    .catch((error) => {
      console.error(error);
      showToast('发送验证码失败');
    });
}

function startCountdown() {
  let remainingTime = 5;
  countdown.value = remainingTime;

  const intervalId = setInterval(() => {
    if (remainingTime > 0) {
      remainingTime--;
      countdown.value = remainingTime;
    } else {
      clearInterval(intervalId);
      countdown.value = null;
    }
  }, 1000);
}

onMounted(() => {
  countdown.value = null;
});

function validateUsername(username: string): boolean {
  const regex = /^[a-zA-Z0-9]{5,8}$/;
  return regex.test(username);
}
function handleSubmit() {
  if (!agreeTerms.value) {
    showToast('请同意用户协议');
    return;
  }

  if (loginMode.value === 'password') {
    if (!username.value || !password.value) {
      showToast('用户名或密码不能为空');
      return;
    }

    if (!validateUsername(username.value)) {
      showToast('用户名必须包含5到8位的大写字母、小写字母或阿拉伯数字');
      return;
    }

    console.log('密码登录:', username.value, password.value);
    // 这里可以添加实际的登录逻辑
  // 调用request请求 /login/password , showToast提示登陆成功 , 并跳转到首页
  request({
    url:'/login/password',
    method:'post',
    data:{
      // mobile 和 password参数
      mobile:'admin',
      password:'123456'
    }
  }).then(res=>{
    showToast('登录成功')
    router.push('/')
  })

  } else {
    console.log('验证码登录:', phone.value, code.value);
    // 这里可以添加实际的验证码登录逻辑


    // 手机号不允许为空
    if (!validatePhoneNumber(phone.value)) {
      showToast('请输入有效的11位手机号码');
      return;
    }

    // 验证码不允许为空
    if (!code.value) {
      showToast('验证码不能为空');
      return;
    }

  // 调用request请求 /login, showToast提示登陆成功 , 并跳转到首页
  request({
    url:'/login',
    method:'post',
    data:{
      // mobile 和 code参数
      mobile:'15244667237',
      code:'123456'
    }
  }).then(res=>{
    showToast('登录成功')
    router.push('/')
  })

  }



}
</script>

<style lang="scss" scoped>

.login-form {
  width: 100%;
  max-width: 400px;
  margin-top: 20px;
}

.van-nav-bar__title {
  font-size: 20px;
  font-weight: bold;
}

.van-nav-bar__left {
  font-size: 18px;
}

.van-nav-bar__right {
  font-size: 16px;
}

.van-cell-group {
  margin-bottom: 20px;
}

.van-field__control {
  font-size: 16px;
}

.van-checkbox__label {
  font-size: 16px;
}

.send-code-button {
  cursor: pointer;
  color: #1989fa;
  font-size: 16px;
}

.login-button {
  margin-top: 20px;
  font-size: 18px;
}
</style>